// pages/index/dayi/dayi.js
import request from '../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    fabiao: [ {
      id: '1',
      userId: 'Tom',
      questionContent: 'California',
      questionTime: '2023-05-10 08:00:00"',

      commonUser: {
          id: '1',
          username: 'user1',
          password: 'pas1',
          nickname: '王我'
      },

      psychologicalAnswers: [
          {
              qid: 'qid',
              questionId: 'question_id',
              replierId: 'replier_id',
              answerContent: 'answer_content',
              answerTime: '2023-06-25 08:00:00',

              consultant: {
                  id: '2',
                  username: 'consultant1',
                  password: 'pas1',
                  nickname: 'kuga'
              }
          },
          {
              qid: 'qid',
              question_id: 'question_id',
              replier_id: 'replier_id',
              answer_content: 'answer_content',
              answer_time: '2023-06-25 08:00:00',
              consultant: {
                  id: '3',
                  username: 'consultant2',
                  password: 'pas1',
                  nickname: 'kuga'
              }
          },
      ],
  }]
  },

  onClickLeft: function() {
    wx.navigateBack()
  },

  turnZT(e) {
    wx.setStorageSync('question', this.data.fabiao[e.currentTarget.dataset.index])
    wx.navigateTo({
      url: '/pages/index/dayi/zhuti/zhuti',
    })
  },

  onChange(event) {
    wx.showToast({
      title: `切换到标签 ${event.detail.name}`,
      icon: 'none',
    });
    switch(event.detail.name) {
      case 0:
        // 按时间排序
        this.orderByTime()
        console.log(this.data.fabiao)
        break
      case 1:
        //按回复时间排序
        this.orderByAnswerTime()
        console.log(this.data.fabiao)
        break
      case 2:
        //按回复数量排序
        this.orderByAnswerNum()
        console.log(this.data.fabiao)
        break
    }
  },

  //提问按钮
  handleButtonClick() {
    wx.navigateTo({
      url: '/pages/index/tiwen/tiwen',
    })
  },

  async onLoad() {
    const res = await request.get('/dmy/psychologicalQuesion/get', {
      pageNum: 1,
      pageSize: 100
    })
    this.setData({
      fabiao: res.data.list
    })
    this.orderByTime()
  },

  // 按时间排序
  orderByTime() {
    const sorted = this.data.fabiao.sort((a, b) => {
      return new Date(b.questionTime) - new Date(a.questionTime)
    })
    this.setData({ fabiao: sorted })
  },


// 按回复时间排序
// 按回答时间排序
orderByAnswerTime() {
  console.log("排序前数据:", JSON.stringify(this.data.fabiao.map(item => item.id)));
  
  // 深拷贝原数组以避免引用问题
  const dataToSort = JSON.parse(JSON.stringify(this.data.fabiao));
  
  const sorted = dataToSort.sort((a, b) => {
    // 获取最新回答时间
    const aTime = this.getLatestAnswerTime(a);
    const bTime = this.getLatestAnswerTime(b);
    
    console.log(`问题ID: ${a.id} 最新回答时间: ${new Date(aTime).toLocaleString()}`);
    console.log(`问题ID: ${b.id} 最新回答时间: ${new Date(bTime).toLocaleString()}`);
    
    // 无回答的问题排在后面，使用提问时间
    if (aTime === 0 && bTime === 0) {
      const aQTime = new Date(a.questionTime).getTime();
      const bQTime = new Date(b.questionTime).getTime();
      return bQTime - aQTime; // 提问时间降序
    }
    
    if (aTime === 0) return 1;  // a无回答排后面
    if (bTime === 0) return -1; // b无回答排后面
    
    // 回答时间降序排序
    return bTime - aTime;
  });
  
  console.log("排序后数据:", JSON.stringify(sorted.map(item => item.id)));
  this.setData({ fabiao: sorted });
},

// 获取最新回答时间
getLatestAnswerTime(question) {
  // 无回答处理
  if (!question.psychologicalAnswers || question.psychologicalAnswers.length === 0) {
    return 0;
  }
  
  let latestTime = 0;
  
  for (const answer of question.psychologicalAnswers) {
    // 处理两种可能的属性名
    const timeString = answer.answerTime || answer.answer_time;
    
    if (!timeString) continue;
    
    try {
      // 尝试解析时间字符串
      let timestamp;
      
      // 针对不同时间格式进行处理
      if (timeString.includes('-')) {
        // 标准日期格式 "2023-06-25 08:00:00"
        timestamp = new Date(timeString.replace(' ', 'T')).getTime();
      } else {
        // 尝试直接解析
        timestamp = new Date(timeString).getTime();
      }
      
      // 检查时间戳是否有效
      if (!isNaN(timestamp) && timestamp > latestTime) {
        latestTime = timestamp;
        console.log(`问题ID: ${question.id}, 更新最新回答时间: ${new Date(latestTime).toLocaleString()}`);
      }
    } catch (error) {
      console.error(`时间解析错误: ${timeString}`, error);
    }
  }
  
  return latestTime;
},

  //按回复数量排序
  orderByAnswerNum() {
    const sorted = this.data.fabiao.sort((a, b) => {
      const aCount = a.psychologicalAnswers?.length || 0
      const bCount = b.psychologicalAnswers?.length || 0
      return bCount - aCount
    })
    this.setData({ fabiao: sorted })
  }
})